const Cart = {
    state: {
        cart: JSON.parse(localStorage.getItem("cart")) || [],
        checked: false,
    },
    mutations: {
        getCart(state, item) {
            let rel = false
            state.cart.forEach((element) => {
                if (element.id === item.id) {
                    element.num++
                    rel = true
                }
            })
            if (!rel) {
                state.cart.push(item)
                item.num = 1
                item.checked = false
            }
            localStorage.setItem("cart", JSON.stringify(state.cart))
        },
        //步进器加
        jia(state, item) {
            state.cart.forEach(element => {
                // console.log(element);
                if (element.id === item.id) {
                    element.num++
                }
            })
            localStorage.setItem("cart", JSON.stringify(state.cart))
        },
        jian(state, item) {
            state.cart.forEach(element => {
                if (element.id === item.id) {
                    if (element.num <= 0) {
                        element.num = 1
                    } else {
                        element.num--
                    }
                }
            })
            localStorage.setItem("cart", JSON.stringify(state.cart))
        },
        del(state, index) {
            state.cart.splice(index, 1)
            localStorage.setItem("cart", JSON.stringify(state.cart))
        },
        checked(state, item) {
            state.cart.forEach(element => {
                if (element.id === item.id) {
                    element.checked = item.checked
                    console.log(element.checked);
                }
            })
            localStorage.setItem("cart", JSON.stringify(state.cart))
        },
        checkeds(state, item) {
            state.cart.forEach(element => {
                element.checked = item
            })
            localStorage.setItem("cart", JSON.stringify(state.cart))
        }
    },
    actions: {
        getCart(content, item) {
            content.commit("getCart", item)
        },
        jia(content, item) {
            content.commit("jia", item)
        },
        jian(content, item) {
            content.commit("jian", item)
        },
        del(content, item) {
            content.commit("del", item)
        },
        checked(content, item) {
            content.commit("checked", item)
        }
    },
    getters: {
        price: function (state) {
            var temp = 0
            state.cart.forEach(element => {
                if (element.checked) {
                    temp += element.num * element.originalPrice * 100
                }
            })
            return temp
        }
    }
}
export default Cart